package com.ktgj.customer.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.common.core.utils.helper.CloneHelper;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.vo.CustomerIdVo;
import com.ktgj.customer.domain.vo.IntegralVo;
import com.ktgj.customer.domain.vo.PointRecordListVo;
import com.ktgj.customer.mapper.*;
import com.ktgj.customer.service.ICustomerService;
import com.ktgj.customer.service.ILoginService;
import com.ktgj.flight.api.RemoteFlightService;
import com.ktgj.flight.api.domain.FlightOrderInfo;
import com.ktgj.hotel.api.RemoteHotelService;
import com.ktgj.hotel.api.domain.HotelOrder;
import com.ktgj.service.api.RemoteService;
import com.ktgj.service.api.domain.OrderBoarding;
import com.ktgj.service.api.domain.OrderVipchannel;
import com.ktgj.service.api.domain.OrderViphall;
import com.ktgj.train.api.RemoteTrainService;
import com.ktgj.train.api.domain.TrainOrder;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.customer.service.IPointRecordService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * 积分明细
 * Service业务层处理
 *
 * @author ruoyi
 * @date 2021-07-27
 */
@Service
@Transactional
public class PointRecordServiceImpl implements IPointRecordService {
    @Autowired
    private PointRecordMapper pointRecordMapper;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private CustomerRightdetailMapper customerRightdetailMapper;
    @Autowired
    private DepositBusinessMapper depositBusinessMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IPointRecordService pointRecordService;
    @Autowired
    private ILoginService loginService;
    @Autowired
    private RemoteHotelService remoteHotelService;
    @Autowired
    private RemoteFlightService remoteFlightService;
    @Autowired
    private RemoteService remoteService;
    @Autowired
    private RemoteTrainService remoteTrainService;
    @Autowired
    private BusinessOrderMapper businessOrderMapper;
    @Autowired
    private CustomerMapper customerMapper;

    /**
     * 查询积分明细
     *
     * @param pntRecordId 积分明细
     *                    ID
     * @return 积分明细
     */
    @Override
    public PointRecord selectPointRecordById(Long pntRecordId) {
        return pointRecordMapper.selectPointRecordById(pntRecordId);
    }

    /**
     * 查询积分明细
     * 列表
     *
     * @param pointRecord 积分明细
     * @return 积分明细
     */
    @Override
    public List<PointRecord> selectPointRecordList(PointRecord pointRecord) {
        return pointRecordMapper.selectPointRecordList(pointRecord);
    }

    /**
     * 新增积分明细
     *
     * @param pointRecord 积分明细
     * @return 结果
     */
    @Override
    public int insertPointRecord(PointRecord pointRecord) {
        return pointRecordMapper.insertPointRecord(pointRecord);
    }

    /**
     * 修改积分明细
     *
     * @param pointRecord 积分明细
     * @return 结果
     */
    @Override
    public int updatePointRecord(PointRecord pointRecord) {
        return pointRecordMapper.updatePointRecord(pointRecord);
    }

    /**
     * 批量删除积分明细
     *
     * @param pntRecordIds 需要删除的积分明细
     *                     ID
     * @return 结果
     */
    @Override
    public int deletePointRecordByIds(Long[] pntRecordIds) {
        return pointRecordMapper.deletePointRecordByIds(pntRecordIds);
    }

    /**
     * 删除积分明细
     * 信息
     *
     * @param pntRecordId 积分明细
     *                    ID
     * @return 结果
     */
    @Override
    public int deletePointRecordById(Long pntRecordId) {
        return pointRecordMapper.deletePointRecordById(pntRecordId);
    }

    @Override
    //给会员加积分
    //(消费金额，订单描述，记录编号，员工信息ID，客户基本信息ID，对应订单类型，对应订单号，原因详细说明)
    public int addPointRecord(BigDecimal price, String orderSourceDesc, Long employeeId, Long customerId, String orderType, Long orderId, String pntReasonDesc) {
        Date date = DateUtils.getNowDate();
        PointRecord pointRecord = new PointRecord();
//        pointRecord.setExpiredTime(DateUtils.addMonths(date, 12));
        Long availableValue = price.longValue();
        pointRecord.setAvailableValue(availableValue);
        pointRecord.setOrderSourceDesc(orderSourceDesc);
        pointRecord.setEmployeeId(employeeId);
        pointRecord.setCustomerId(customerId);
        pointRecord.setOrderType(orderType);
        pointRecord.setPntValue(availableValue);
        pointRecord.setPntReasonDesc(pntReasonDesc);
        pointRecord.setOrderId(orderId);
        pointRecord.setOperationTime(date);
        pointRecord.setPntDirection(1L);
        pointRecord.setAudit("false");
        return pointRecordMapper.insertPointRecord(pointRecord);
    }

    @Override
    //查询当前可用积分
    public Long queryUserCreditsNum(Long customerId) {
        Long i = 0l;
        List<PointRecord> pointRecordList = pointRecordMapper.queryUserCreditsNum(customerId);
        if (pointRecordList != null && pointRecordList.size() > 0){
            i = pointRecordList.get(0).getAvailableValue();
        }
        return i;
    }

    /**
     * 查询当前用户的积分
     * */
    @Override
    public IntegralVo queryUserCredits(Long customerId) throws Exception {
        IntegralVo integralVo = new IntegralVo();
        //当前用户可用积分
        Long integal;
        try {
            integal = queryUserCreditsNum(customerId);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

        Long maturity = pointRecordMapper.queryUserMaturityNum(customerId);
        List<PointRecord> pointRecordList = pointRecordMapper.queryUserUseNum(customerId);

        if (maturity != null && maturity != 0){
            integralVo.setExpiryReminder(maturity + "积分即将到期");
        }
        else {
            integralVo.setExpiryReminder("0积分即将到期");
        }
        Long pointSum = 0l;
        for (PointRecord pointRecord :pointRecordList)
        {
            pointSum += pointRecord.getAvailableValue();
        }
        integralVo.setUsedPointsAvailable(pointSum);
        integralVo.setPointsAvailable(integal);
        return integralVo;
    }

    @Override
    public int signIn(Long customerId) {
        SimpleDateFormat dateInfo = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        BigDecimal price;
        PointRecord pointRecord = pointRecordMapper.querySignInReCord(customerId);
        if (pointRecord == null)
            price = new BigDecimal(1);
        else if (dateInfo.format(DateUtils.addDays(pointRecord.getOperationTime(), 1)).equals(dateInfo.format(date))) {
            if (pointRecord.getPntValue().longValue() < 7)
                price = new BigDecimal(pointRecord.getPntValue() + 1);
            else
                price = new BigDecimal(7);
        } else
            price = new BigDecimal(1);
        return addPointRecord(price, "注册赠送积分", 1L, customerId, CustomerConstants.signIn.getValue(), null, null);//(消费金额，订单描述，记录编号，员工信息ID，客户基本信息ID，对应订单类型，对应订单号，原因详细说明)
    }

    /**
     * 花费积分
     *
     * @param customerId      会员id
     * @param creditsNum      要扣减的积分
     * @param orderType       订单类型
     * @param orderId         订单id
     * @param orderSourceDesc 订单描述（客户端展示使用），例如机票 显示航程+航班号
     * @param couponId        使用优惠卷的id
     * @return
     */
    @Override
    public String spend(Long customerId, Long creditsNum, String orderType, Long orderId, String orderSourceDesc, Long couponId, Long employeeId) throws Exception {//会员id、要扣减的积分、订单类型、订单id、订单描述（客户端展示使用），例如机票 显示航程+航班号、使用优惠卷的id、预留款、操作员工id
//        if (creditsNum != null && creditsNum.longValue() > 0l) {
//            PointRecord pointRecord = new PointRecord();
//            List<PointRecord> pointRecords = pointRecordMapper.queryUsablePointRecordList(customerId);
//            Long num = CloneHelper.deepClone(creditsNum);
//            List<Long> ids = new ArrayList<>();
//            for (PointRecord item : pointRecords) {
//                if (item.getAvailableValue() < num) {
//                    ids.add(item.getPntRecordId());
//                    num = num - item.getAvailableValue();
//                } else if (item.getAvailableValue().equals(num)) {
//                    ids.add(item.getPntRecordId());
//                    break;
//                } else {
//                    item.setAvailableValue(item.getAvailableValue() - num);
//                    pointRecordMapper.updatePointRecord(item);
//                    break;
//                }
//            }
//            if (ids.size() > 0)
//                pointRecordMapper.updateAvailableValueEqualZero(ids);
//            pointRecord.setAvailableValue(0L);
//            pointRecord.setEmployeeId(employeeId);
//            pointRecord.setCustomerId(customerId);
//            pointRecord.setPntValue(creditsNum);
//            pointRecord.setOrderType(orderType);
//            pointRecord.setOrderId(orderId);
//            pointRecord.setOperationTime(new Date());
//            pointRecord.setPntDirection(2L);
//            pointRecord.setOrderSourceDesc(orderSourceDesc);
//            pointRecord.setAudit("false");
//            pointRecordMapper.insertPointRecord(pointRecord);
//        }
        PointRecord pointRecord = new PointRecord();
        pointRecord.setOrderSourceDesc(orderSourceDesc);
        pointRecord.setEmployeeId(employeeId);
        pointRecord.setCustomerId(customerId);
        pointRecord.setOrderType(orderType);
        pointRecord.setPntValue(creditsNum);
        pointRecord.setOrderId(orderId);
        pointRecord.setOperationTime(new Date());
        pointRecord.setPntDirection(2l);
        try {
            integralOperation(pointRecord);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        if (couponId != null) {
            //修改优惠卷状态
            CustomerRightdetail customerRightdetail = new CustomerRightdetail();
            customerRightdetail.setCustomerRightdetailId(couponId);
            customerRightdetail.setRightdetailState(CustomerConstants.valid.getValue());
            customerRightdetailMapper.updateCustomerRightdetail(customerRightdetail);
        }

//        if (usedDeposit != null && usedDeposit.compareTo(new BigDecimal(0)) == 1) {
//            List<DepositBusiness> depositBusinesses = depositBusinessMapper.queryUsableDepositBusinessList(customerId);
//            BigDecimal num = CloneHelper.deepClone(usedDeposit);
//            List<Long> ids = new ArrayList<>();
//            for (DepositBusiness item : depositBusinesses) {
//                if (item.getAmount().compareTo(num) == -1) {
//                    ids.add(item.getBusinessId());
//                    num = num.subtract(item.getAmount());
//                } else if (item.getAmount().compareTo(num) == 0) {
//                    ids.add(item.getBusinessId());
//                    break;
//                } else {
//                    item.setAmount(item.getAmount().subtract(num));
//                    depositBusinessMapper.updateDepositBusiness(item);
//                    break;
//                }
//            }
//            if (ids.size() > 0)
//                depositBusinessMapper.updateAmountEqualZero(ids);
//
//            DepositBusiness depositBusiness = new DepositBusiness();
//            depositBusiness.setBusinessType(orderType);//订单来源类型
//            depositBusiness.setOperatorId(employeeId);//操作员id
//            depositBusiness.setCustomerId(customerId);//会员id
//            depositBusiness.setDetailamount(usedDeposit.multiply(new BigDecimal(-1)));//明细金额
//            depositBusiness.setChangetype(2L);//方向（1增2减）
//            depositBusiness.setOrderId(orderId);//订单id
//            depositBusiness.setAmount(new BigDecimal(0));
//            depositBusiness.setState(EmHelper.Audit.NotReviewed.getValue());
//            depositBusinessMapper.insertDepositBusiness(depositBusiness);
//        }

        return "success";
    }

    /**
     * 积分记录列表
     * */
    @Override
    public List<PointRecord> pointRecordList(PointRecordListVo pointRecordListVo) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<PointRecord> pointRecordList = pointRecordMapper.pointRecordList(pointRecordListVo);

        Long aLong = 0l;
        if (pointRecordListVo.getId() != 0){
            aLong = pointRecordService.queryUserCreditsNum(pointRecordListVo.getId());
        }

        if (pointRecordList != null && pointRecordList.size() > 0){
            for (PointRecord pointRecord : pointRecordList) {
                Customer customer = customerMapper.selectCustomerById(pointRecord.getCustomerId());
                if (customer != null){
                    pointRecord.setCustomerName(customer.getCustomerName());
                    pointRecord.setPhone(customer.getContractPhoneOne());
                }

                if (pointRecord.getAuditEmployeeId() != null){
                    Employee employee = employeeMapper.backSelectEmployee(pointRecord.getAuditEmployeeId());
                    if (employee != null){
                        pointRecord.setAuditEmployeeName(employee.getEmployeeName());
                    }
                }

                if (pointRecord.getAuditOperationTime() != null){
                    pointRecord.setAuditOperationDate(format.format(pointRecord.getAuditOperationTime()));
                }

                if (pointRecord.getOrderId() != null && pointRecord.getOrderId() != 0){
                    pointRecord.setOrderNum(pointRecord.getOrderId().toString());
                }

                if (aLong != null && aLong != 0){
                    pointRecord.setIntegral(aLong.toString());
                }

                Employee employee = employeeMapper.selectEmployeeById(pointRecord.getEmployeeId());
                if (employee != null){
                    pointRecord.setEmployeeName(employee.getEmployeeName());
                }
                if (pointRecord.getOperationTime() != null){
                    pointRecord.setOperationDate(format.format(pointRecord.getOperationTime()));
                }
                if (pointRecord.getPntDirection() != null){
                    if (pointRecord.getPntDirection() == 1){
                        pointRecord.setTmpPntValue("+" + pointRecord.getPntValue());
                    }
                    else if (pointRecord.getPntDirection() == 2){
                        pointRecord.setTmpPntValue("-" + pointRecord.getPntValue());
                    }
                }
            }
        }
        return pointRecordList;
    }

    /**
     * 会员积分调整
     * */
    @Override
    public int adjustment(PointRecord pointRecord, HttpServletRequest request) throws Exception {
        //酒店
        if (pointRecord.getOrderType().equals(EmHelper.businessType.HOTEL.getValue())){
            Map<String, Object> map = new HashMap<>();
            map.put("orderNum", pointRecord.getOrderNum());
            HotelOrder order = remoteHotelService.orderNum(map);
            if (order == null){
                pointRecord.setOrderNum(null);
            }
        }
        //机票
        else if (pointRecord.getOrderType().equals(EmHelper.businessType.FLIGHT.getValue())){
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", pointRecord.getOrderNum());
            FlightOrderInfo order = remoteFlightService.order(map);
            if (order == null){
                pointRecord.setOrderNum(null);
            }
        }
        //贵宾厅
        else if (pointRecord.getOrderType().equals(EmHelper.businessType.SERVICE.getValue())){
            Map<String, Object> map = new HashMap<>();
            map.put("orderNum", pointRecord.getOrderNum());
            OrderViphall orderViphall = remoteService.orderNum(map);
            if (orderViphall == null){
                pointRecord.setOrderNum(null);
            }
        }
        //火车票
        else if (pointRecord.getOrderType().equals(EmHelper.businessType.TRAIN.getValue())){
            Map<String, Object> map = new HashMap<>();
            map.put("orderNum", pointRecord.getOrderNum());
            TrainOrder trainOrder = remoteTrainService.orderNum(map);
            if (trainOrder == null){
                pointRecord.setOrderNum(null);
            }
        }
        //vip通道
        else if (pointRecord.getOrderType().equals(EmHelper.businessType.VIPAisle.getValue())){
            Map<String, Object> map = new HashMap<>();
            map.put("orderNum", pointRecord.getOrderNum());
            OrderVipchannel orderVipchannel = remoteService.orderVipchannel(map);
            if (orderVipchannel == null){
                pointRecord.setOrderNum(null);
            }
        }
        //值机
        else if (pointRecord.getOrderType().equals(EmHelper.businessType.CheckIn.getValue())){
            Map<String, Object> map = new HashMap<>();
            map.put("orderNum", pointRecord.getOrderNum());
            OrderBoarding orderBoarding = remoteService.orderBoarding(map);
            if (orderBoarding == null){
                pointRecord.setOrderNum(null);
            }
        }
        //会员
        else if (pointRecord.getOrderType().equals(EmHelper.businessType.Customer.getValue())){
            BusinessOrder businessOrder = businessOrderMapper.selectBusinessOrderByOrdernum(pointRecord.getOrderNum());
            if (businessOrder == null){
                pointRecord.setOrderNum(null);
            }
        }

        String token = request.getHeader("token");
        Employee loginEmployeeByToken = loginService.getLoginEmployeeByToken(token);
        if (loginEmployeeByToken == null){
            throw new Exception("登陆已过期");
        }
        pointRecord.setEmployeeId(loginEmployeeByToken.getEmployeeId());

        Date date = new Date();
        pointRecord.setOperationTime(date);

        if (pointRecord.getOrderNum() != null && !pointRecord.getOrderNum().equals("")){
            pointRecord.setOrderId(Long.valueOf(pointRecord.getOrderNum()));
        }

        pointRecord.setAudit("false");
        int i = pointRecordMapper.insertPointRecord(pointRecord);
        return i;
    }

    /**
     * 积分审核
     * */
    @Override
    public int pointReview(HttpServletRequest request, Long id) throws Exception {
        Date date = new Date();
        String token = request.getHeader("token");
        Employee loginEmployeeByToken = loginService.getLoginEmployeeByToken(token);
        if (loginEmployeeByToken == null){
            throw new Exception("登陆已过期");
        }

        //获取积分记录
        PointRecord pointRecord = pointRecordMapper.selectPointRecordById(id);
        List<PointRecord> pointRecordList = pointRecordMapper.statistics(pointRecord.getCustomerId());
        Long pntValue = 0l;
        if (pointRecord.getPntDirection() == 2){
            pntValue = pointRecord.getPntValue();
        }

        if (pointRecordList != null && pointRecordList.size() > 0){
            PointRecord tmpPointRecord = new PointRecord();
            tmpPointRecord.setPntRecordId(pointRecord.getPntRecordId());
            tmpPointRecord.setUsedIntegral(0l);
            if (pointRecord.getAvailableValue() != null)
                tmpPointRecord.setAvailableValue(pointRecord.getAvailableValue());
            else
                tmpPointRecord.setAvailableValue(pointRecordList.get(0).getAvailableValue());
            tmpPointRecord.setPntValue(pntValue);
            pointRecordList = new ArrayList<>();
            pointRecordList.add(tmpPointRecord);
        }

        //增加
        if (pointRecord.getPntDirection() == 1){
            pointRecord.setPntRecordId(id);
            pointRecord.setAudit("true");
            pointRecord.setAuditEmployeeId(loginEmployeeByToken.getEmployeeId());
            pointRecord.setAuditOperationTime(date);

            if (pointRecordList != null && pointRecordList.size() > 0 && pointRecordList.get(0).getUsedIntegral() != null){
                pointRecord.setUsedIntegral(pointRecordList.get(0).getUsedIntegral());
            }
            else {
                pointRecord.setUsedIntegral(0l);
            }

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.YEAR, 1);

            //过期时间 = 审核通过时间 + 1年；
            pointRecord.setExpiredTime(calendar.getTime());

            Long aLong = integralStatistics(pointRecord.getCustomerId());
            if (aLong != -1){
                pointRecord.setAvailableValue(aLong);
            }
            else {
                pointRecord.setAvailableValue(pointRecord.getPntValue());
            }
            int i = pointRecordMapper.updatePointRecord(pointRecord);
            if (i <= 0){
                throw new Exception("审核失败");
            }

            Long integralStatistics = integralStatistics(pointRecord.getCustomerId());
            if (integralStatistics != -1){
                pointRecord.setAvailableValue(integralStatistics);
            }
            else {
                pointRecord.setAvailableValue(0l);
            }
            i = pointRecordMapper.updatePointRecordByCustomerId(pointRecord);
            return i;
        }
        //减少
        else {
            //当前会员可用总积分小于减少数量
            if (pointRecordList != null && pointRecordList.size() > 0 && pointRecordList.get(0).getAvailableValue() < pointRecord.getPntValue()){
                for (PointRecord record : pointRecordList) {
                    record.setAvailableValue(record.getAvailableValue() - pointRecord.getPntValue());
                    record.setPntDirection(2l);
                    record.setPntValue(0l);
                    record.setAuditEmployeeId(loginEmployeeByToken.getEmployeeId());
                    record.setAuditOperationTime(date);
                    record.setAudit("true");
                    int i = pointRecordMapper.updateStatistics(record);
                    return i;
                }
            }
            //当前会员可用总积分大于或等于减少数量
            else {
                //过期时间转毫秒
                for (PointRecord tmpPointRecord : pointRecordList) {
                    tmpPointRecord.setMillisecond(pointRecord.getExpiredTime().getTime());
                }
                //从小到大排序
                pointRecordList.sort((x, y) -> Double.compare(x.getMillisecond(), y.getMillisecond()));

                //第一条数据为会员所有未过期的增加积分记录中，剩余有效期最短的
                for (PointRecord record : pointRecordList) {
                    /*if (pointRecord.getPntValue() > 0){
                        if (record.getPntValue() < pointRecord.getPntValue()){
                            pointRecord.setPntValue(pointRecord.getPntValue() - record.getPntValue());

                            record.setPntValue(0l);
                            record.setPntDirection(2l);
                        }
                        //当前记录中的积分数量大于或等于减少数量
                        else {
                            record.setPntValue(record.getPntValue() - pointRecord.getPntValue());
                            pointRecord.setPntValue(0l);

                            if (record.getPntValue() == 0){
                                record.setPntDirection(2l);
                            }
                        }
                    }*/

                    record.setPntDirection(2l);
                    record.setAvailableValue(record.getAvailableValue() - pntValue);

                    //更新会员已使用积分
                    if (record.getUsedIntegral() == null){
                        record.setUsedIntegral(pntValue);
                    }
                    else {
                        record.setUsedIntegral(record.getUsedIntegral() + pntValue);
                    }
                    record.setAuditEmployeeId(loginEmployeeByToken.getEmployeeId());
                    record.setAuditOperationTime(date);
                    record.setAudit("true");
                    int i = pointRecordMapper.updatePointRecord(record);
                    if (i <= 0){
                        throw new Exception("更新会员已使用积分失败");
                    }
                    Long point = record.getAvailableValue();
                    record = new PointRecord();
                    record.setCustomerId(pointRecord.getCustomerId());
                    record.setAvailableValue(point);
                    pointRecordMapper.updatePointRecordByCustomerId(record);
                }
            }
        }
        return 1;
    }

    /**
     * 积分统计
     * */
    @Override
    public Long integralStatistics(Long customerId) throws Exception {
        //记录统计后的会员总积分
        Long integral = 0l;
        //获取会员所有未过期的积分记录
        List<PointRecord> pointRecordList = pointRecordMapper.integralStatistics(customerId);
        //统计会员当前可支配的积分数量，统计前默认为0
        if (pointRecordList != null && pointRecordList.size() > 0){
            for (PointRecord pointRecord : pointRecordList) {
                //积分方向为1，表示该条记录为增加积分
                if (pointRecord.getPntDirection() == 1){
                    integral = integral + pointRecord.getPntValue();
                }
                //积分方向为2，表示该条记录为减少积分
                else if (pointRecord.getPntDirection() == 2){
                    integral = integral - pointRecord.getPntValue();
                }
                //其他方向为无效数据，需明确积分方向后，才能继续操作
                else {
                    throw new Exception("不明确的积分方向，请联系工作人员进行核实数据");
                }
            }
        }
        //会员没有积分记录，返回会员总积分为-1, 并不进行操作
        else {
            return -1l;
        }
        return integral;
    }

    /**
     * 积分操作
     * */
    @Transactional
    @Override
    public boolean integralOperation(PointRecord pointRecord) throws Exception {
        Long aLong;
        try {
            aLong = integralStatistics(pointRecord.getCustomerId());
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }
//        if (aLong == -1 && pointRecord.getPntDirection() == 2){
//            throw new Exception("当前用户积分不足");
//        }

        if (aLong == -1){
            pointRecord.setAvailableValue(0l);
        }
        else {
            pointRecord.setAvailableValue(aLong);
        }
        pointRecord.setAudit("false");
        int i = pointRecordMapper.insertPointRecord(pointRecord);
        if (i <= 0){
            return false;
        }
        return true;
    }

    /**
     * 当前会员可支配积分
     * */
    @Override
    public Long dominateIntegral(Long id) {
        Long integral = 0l;
        List<PointRecord> pointRecordList = pointRecordMapper.dominateIntegral(id);
        if (pointRecordList != null &&pointRecordList.size() > 0){
            integral = pointRecordList.get(0).getAvailableValue();
            for (PointRecord pointRecord : pointRecordList) {
                if (pointRecord.getAudit().equals("false") && pointRecord.getPntDirection() == 2){
                    integral = integral - pointRecord.getPntValue();
                }
            }
        }
        return integral;
    }
}
